package cn.com.cetccst.dataupload.sync.restriction;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.RestrictionStatusEntity;
import cn.com.cetccst.dataupload.network.DataUploadHttpRequester;
import cn.com.cetccst.tools.log.CommonLogger;
import retrofit2.Response;

public class UploadRestrictionWorker extends Worker {

    private static final String CMD_NAME = "commands.DevicePolicyStatusCmd";

    public UploadRestrictionWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        CommonLogger.info("uploading restriction records");
        List<RestrictionStatusEntity> allStatus = PolicyRepository.getInstance().getRestrictionStatus();
        try {
            Response<JSONObject> response = DataUploadHttpRequester.getInstance().requestUploadData(CMD_NAME, buildPayload(allStatus));
            if (response == null || !response.isSuccessful())
                return Result.retry();
        } catch (IOException e) {
            CommonLogger.error("upload restriction records error", e);
            return Result.retry();
        }
        return Result.success();
    }

    private String buildPayload(List<RestrictionStatusEntity> entities) {

        Map<String, Object> statusBody = new HashMap<>();
        for(RestrictionStatusEntity entity : entities) {
            Map<String, Object> object = new HashMap<>();
            object.put("expectedVal", entity.getExpected());
            object.put("actualVal", entity.getActual());
            statusBody.put(entity.getName(), object);
        }
        return new Gson().toJson(statusBody);
    }
}
